// pages/orderpage/orderpage.js
const app = getApp()
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

// const recorderManager = wx.getRecorderManager()
Page({
  //开始录音的时候
  start: function () {
    //https://www.cnblogs.com/danielWise/p/9020884.html
    const options = {
      duration: 10000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },

  //停止录音
  stop: function () {
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
    })
  },


  //播放声音
  play: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  data: {

    j: 1,//帧动画初始图片  

    isSpeaking: false,//是否正在说话  

    voices: [],//音频数组  
    tempFilePathss: '',
  },

  onLoad: function () {

  },  
  //拍照
  pic: function (options) {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
      }
    })
  },
  fail: function (res) {
    console.log(res.errMsg)
  },

  //扫二维码
  click: function () {
    var that = this;
    var show;
    wx.scanCode({
      success: (res) => {
        this.show = "结果:" + res.result + "二维码类型:" + res.scanType + "字符集:" + res.charSet;
        that.setData({
          show: this.show
        })
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: (res) => {
        wx.showToast({
          title: '失败',
          icon: 'success',
          duration: 2000
        })
      },
      complete: (res) => {
      }
    })
  },

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    url: {
      "fault_type": app.data.ull +"wxSelectFault",
      "fault_info": app.data.ull +"wxSelectFaultinfo",
      "add_order": app.data.ull +"wxAddOrder"
    },
    fault_type: ({
    }),
    index: 0,
    info_index: 0,
    region: [],
    faultinfo: ({}),
    userId: 123,
    inputShow: 'none',
    selectShow: 'block',
    fault_type_input: "",
    orderId: "",
    address: {},
    tepvalue: "请选择地址",
    index_type:"",
  },
  //故障信息详情
  showFaultInfo: function () {
    var that = this;
    // wx.request({
    //   url: that.data.url.fault_info,
    //   data: {
    //     faulttype: that.data.fault_type[that.data.index],
    //   },
    //   header: {
    //     "Content-Type": "applciation/json"
    //   },
    //   method: "GET",
    //   success: function (res) {
    //     var a = [];
    //     var json = res.data;
    //     for (var j in json) {
    //       a.push(json[j].faultinfo);
    //     }
    //     that.setData({//如果在sucess直接写this就变成了wx.request()的this了.必须为getdata函数的this,不然无法重置调用函数
    //       faultinfo: a,
    //       inputShow: 'none'
    //     })
    //   },
    //   fail: function (res) { },
    //   complete: function (res) {
    //   },
    // })
  },
  //故障类型选择
  bindpickerchange: function (e) {
    var that = this;
    that.setData({
      index: e.detail.value,
      info_index: 0
    })
    if (that.data.fault_type[that.data.index] == "其他") {
      that.setData({
        inputShow: 'block',
        faultinfo: ({}),
      })
    } else {
      that.showFaultInfo();
    }
  },
  //故障信息输入
  faultTypeInputlur: function (e) {
    var fault_type_input = e.detail.value;
    if (fault_type_input.length < 10 && fault_type_input.length > 0) {
      this.setData({
        fault_type_input: e.detail.value
      })
    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '其他故障详情有误，请重新输入',
      })
    }
  },
  //故障信息选择
  bindinfochange: function (e) {
    this.setData({
      info_index: e.detail.value,
    })

  },
  //订单提交
  gonext: function (e) {
    var that = this;
    var finalfaultinfo = "";

    if (that.data.fault_type[that.data.index] == "其他") {
      finalfaultinfo = that.data.fault_type_input;
    } else {
      finalfaultinfo = that.data.faultinfo[that.data.info_index]
    }
    if (that.data.tepvalue == "" && finalfaultinfo.length < 10 && finalfaultinfo.length > 0) {
    // wx.request({
    //   url: that.data.url.add_order,
    //   data: {
    //     name:that.data.address.userName,
    //     faulttype: that.data.fault_type[that.data.index],
    //     faultinfo: finalfaultinfo,
    //     userId: app.data.user.id,
    //     region: that.data.address.provinceName + that.data.address.cityName + that.data.address.countyName + that.data.address.detailInfo,
    //   },
    //   header: {
    //     "Content-Type": "applciation/json"
    //   },
    //   method: "GET",
    //   success: function (res) {
    //     that.setData({//如果在sucess直接写this就变成了wx.request()的this了.必须为getdata函数的this,不然无法重置调用函数
    //       orderId: res.data,//返回订单号
    //     })
    //     wx.showToast({
    //       title: '下单成功',
    //       icon: 'success',
    //       image: '',
    //       duration: 2000,
    //       mask: true,
    //       success: function (res) {
    //         wx.navigateTo({
    //           url: '../orderinfo/orderinfo?orderId=' + that.data.orderId,
    //           success: function (res) { },
    //           fail: function (res) { },
    //           complete: function (res) { },
    //         })

    //       },
    //       fail: function (res) { },
    //       complete: function (res) { },
    //     })
    //   },
    //   fail: function (res) { },
    //   complete: function (res) {
    //   },
    // })
    }
    else {
      wx.showToast({
        title: '订单信息不完整',
      })
    }
  },
  //选择省市区函数
  changeRegin(e) {
    this.setData({ region: e.detail.value });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var that = this;
    if(app.data.typeSelected) {
      that.setData({
        index_type: app.data.typeSelected
      })
    }
    that.showFaultInfo();
  },
  //获取故障类型
  getdata: function () {
    var that = this;
    // wx.request({
    //   url: that.data.url.fault_type,
    //   header: {
    //     "Content-Type": "applciation/json"
    //   },
    //   method: "GET",
    //   success: function (res) {
    //     var index;
    //     var a = [];
    //     var json = res.data;
    //     for (var j in json) {
    //       a.push(json[j].type);
    //       if (that.data.index_type == json[j].type) {
    //         index = j;
    //       }
    //     }
    //     a.push("其他")
    //     that.setData({//如果在sucess直接写this就变成了wx.request()的this了.必须为getdata函数的this,不然无法重置调用函数
    //       fault_type: a,
    //     })
    //     that.showFaultInfo();
    //   },
    //   fail: function (res) { },
    //   complete: function (res) {
    //   },
    // })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var list = that.data.list;
    var currentPage = that.data.currentPage;
    that.getdata();
    that.onLoad();
  },
  /**
   * 选择地址
   */
  choseAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        console.log("res",res)
        that.setData({
          address: res,
          region: [res.provinceName, res.cityName, res.countyName],
          tepvalue: "",
        })
      }
    })
  },
  


///////////////////////////
touchdown: function () {
    console.log("手指按下了...")
    console.log("new date : " + new Date)
    var _this = this;
    // debugger;
  const options = {
    duration: 6000,
    sampleRate: 44100,
    numberOfChannels: 1,
    encodeBitRate: 192000,
    format: 'mp3',
  }

    /////////////
  //调取小程序新版授权页面
  wx.authorize({
    scope: 'scope.record',
    success() {
      console.log("录音授权成功");
      //第一次成功授权后 状态切换为2
      _this.setData({
        status: 2,
      })
      // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
      // wx.startRecord();
      // recorderManager.start(options);//使用新版录音接口，可以获取录音文件
    },
    fail() {
      console.log("第一次录音授权失败");
      wx.showModal({
        title: '提示',
        content: '您未授权录音，功能将无法使用',
        showCancel: true,
        confirmText: "授权",
        confirmColor: "#52a2d8",
        success: function (res) {
          if (res.confirm) {
            //确认则打开设置页面（重点）
            wx.openSetting({
              success: (res) => {
                console.log(res.authSetting);
                if (!res.authSetting['scope.record']) {
                  //未设置录音授权
                  console.log("未设置录音授权");
                  wx.showModal({
                    title: '提示',
                    content: '您未授权录音，功能将无法使用',
                    showCancel: false,
                    success: function (res) {

                    },
                  })
                } else {
                  //第二次才成功授权
                  console.log("设置录音授权成功");
                  _this.setData({
                    status: 2,
                  })
                  // recorderManager.start(options);
                }
              },
              fail: function () {
                console.log("授权设置录音失败");
              }
            })
          } else if (res.cancel) {
            console.log("cancel");
          }
        },
        fail: function () {
          console.log("openfail");
        }
      })
    }
  })
////////////////////
    speaking.call(this);
    this.setData({
      isSpeaking: true
    })
    //开始录音  
    wx.startRecord({
      success: function (res) {
        //临时路径,下次进入小程序时无法正常使用  
        var tempFilePath = res.tempFilePath
        console.log("tempFilePath: " + tempFilePath)
        //持久保存  
        wx.saveFile({
          tempFilePath: tempFilePath,
          success: function (res) {
            //持久路径  
            //本地文件存储的大小限制为 100M  
            var savedFilePath = res.savedFilePath
            console.log("savedFilePath: " + savedFilePath)
          }
        })
        wx.showToast({
          title: '恭喜!录音成功',
          icon: 'success',
          duration: 1000
        })
        //获取录音音频列表  
        wx.getSavedFileList({
          success: function (res) {
            var voices ='';
            var filePath='';
            var date='';
            var bo='';
            for (var i = 0; i < res.fileList.length; i++) {
              //格式化时间  
              var createTime = new Date(res.fileList[i].createTime)
              //将音频大小B转为KB  
              var size = (res.fileList[i].size / 1024).toFixed(2);
              var voice = { filePath: res.fileList[i].filePath, createTime: createTime, size: size };
              console.log("文件路径: " + res.fileList[i].filePath)
              console.log("文件时间: " + createTime)
              console.log("文件大小: " + size)
              voices = voices;
              filePath = res.fileList[i].filePath;
              date = createTime;
            }
            _this.setData({
              voices: voices,
              filePath: filePath,
              date: date,
              bo:'show'
            })
          }
        })
      },
      fail: function (res) {
        //录音失败  
        debugger;
        wx.showModal({
          title: '提示',
          content: '录音的姿势不对!',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              return
            }
          }
        })
      }
    })
  },
  //手指抬起  
  touchup: function () {
    console.log("手指抬起了...")
    this.setData({
      isSpeaking: false,
    })
    clearInterval(this.timer)
    wx.stopRecord()
  },
  //点击播放录音  
  gotoPlay: function (e) {
    var filePath = e.currentTarget.dataset.key;
    //点击开始播放  
    wx.showToast({
      title: '开始播放',
      icon: 'success',
      duration: 1000
    })
    wx.playVoice({
      filePath: filePath,
      success: function () {
        wx.showToast({
          title: '播放结束',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  chooseimage: function () {
      var _this = this;
    wx.chooseImage({
      count: 1, // 默认9  
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
     sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
      _this.setData({
        tempFilePaths: res.tempFilePaths  
      })
     
      }  
})
 
  },  
///////////////////////////////////////////////////////////
 chooseImg() {
    let that = this;
    let len = this.data.imgs;
   var type='';
    if (len >= 9) {
      this.setData({
        lenMore: 1
      })
      return;
    }
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      count: 1, 
      success: (res) => {
        let tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        console.log(type)
        let imgs = that.data.imgs;
        for (let i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length < 9) {
            imgs.push(tempFilePaths[i])
          } else {
            that.setData({
              imgs
            })
            wx.showModal({
              title: '提示',
              content: '最多只能有九张图片'
            })
            return;
          }
        }
        that.setData({
          imgs
        })
      }
    })
  },

  previewImg(e) {
    let index = e.currentTarget.dataset.index;
    let imgs = this.data.imgs;
    wx.previewImage({
      current: imgs[index],
      urls: imgs,
    })
  },
  deleteImg(e) {
    let _index = e.currentTarget.dataset.index;
    let imgs = this.data.imgs;
    imgs.splice(_index, 1);
    this.setData({
      imgs
    })
}


})
// 麦克风帧动画  
function speaking() {
  var _this = this;
  //话筒帧动画  
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}